﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TiposComuns.Objectos;

namespace Pesquisa
{
    public partial class Form1 : Form
    {
        private KTree ktree;
        public Form1()
        {
            InitializeComponent();
            ktree = new KTree(new Person("1010",new Address()));
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void LoadTree()
        {
            tree.Nodes.Clear();

            KTree iter = this.ktree;
            
            TreeNode raiz =  new TreeNode("Raiz");

            TreeNode node = new TreeNode("Level 0");
            raiz.Nodes.Add(node);
            int n = 1;
            do
            {
                TreeNode bucs = new TreeNode(String.Format("K-bucket: {0}-{1}",iter.bucket.Order,
                    iter.bucket.Bit));

                
                foreach (Person person in iter.bucket)
                {
                    bucs.Nodes.Add(person.ToString());
                
                }
                node.Nodes.Add(bucs);

                if (iter.right != null)
                {
                    TreeNode right = new TreeNode("Level " + n);
                    node.Nodes.Add(right);

                    node = right;
                    iter = iter.right;
                }
                else if (iter.left != null)
                {
                    TreeNode left = new TreeNode("Level " + n);
                    node.Nodes.Add(left);

                    node = left;
                    iter = iter.left;
                }
                else iter = null;
                
                n++;
            } while (iter != null);

            tree.Nodes.Insert(0, raiz);            
        }

        private void b_adic_Click(object sender, EventArgs e)
        {
            if (tb_name.Text.Length > 0)
            {
                Person person = new Person(tb_name.Text, new Address());
                ktree.Add(person);
                this.LoadTree();
            }
        }

        private void b_rem_Click(object sender, EventArgs e)
        {
            if (tb_name.Text.Length > 0)
            {
                Person person = new Person(tb_name.Text, new Address());
                ktree.Remove(person);
                this.LoadTree();
            }
        }

        private void b_prox_Click(object sender, EventArgs e)
        {
            list.Items.Clear();
            if (tb_prox.Text.Length > 0)
            {                
                foreach (Person p in ktree.GetClosest(new Person(tb_prox.Text, new Address())))
                {
                    list.Items.Add(p.Username);
                }
            }
        }
    }
}
